//
//  HYEditDeviceVC.m
//  TJHYHardwareProduct
//
//  Created by Kendama on 2018/1/22.
//  Copyright © 2018年 Kendama. All rights reserved.
//

#import "HYEditDeviceVC.h"
#import "HYDeviceTypeVC.h"
#import "DTPickerManager.h"
#import "HYDeviceTypeListApi.h"
#import "TWSelectCityView.h"
#import "HYAreaModel.h"
#import "HYGetMainCompanyListApi.h"
#import "HYGetChildCompanyListApi.h"
#import "AlertViewManager.h"
#import "HYAddOrSaveDeviceApi.h"
#import "HYGetDeviceAreaApi.h"
#import "HYDeviceInfoModel.h"

@interface HYEditDeviceVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *titleDataSource;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)UIButton *commitButton;
@property(nonatomic,strong) UIButton *switchButton;
@property(nonatomic,strong)HYDeviceTypeModel *deviceTypeModel;
@property(nonatomic,strong)HYAreaModel *areaModel;
@property(nonatomic,strong)HYMainCompanyModel *companyModel;
@property(nonatomic,strong)HYChildCompanyModel *childCompanyModel;
@property(nonatomic,strong)HYDeviceAreaModel *deviceAreaModel;
@property(nonatomic,copy)NSString *dong;
@property(nonatomic,copy)NSString *ceng;
@property(nonatomic,copy)NSString *fang;
@property(nonatomic,copy)NSString *lostTime;

@end

@implementation HYEditDeviceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)setDeviceInfoModel:(HYDeviceInfoModel *)deviceInfoModel
{
    _deviceInfoModel = deviceInfoModel;
    self.areaModel = [HYAreaModel new];
    self.companyModel = [HYMainCompanyModel new];
    self.deviceTypeModel = [HYDeviceTypeModel new];
    self.childCompanyModel = [HYChildCompanyModel new];
    _areaModel.province = deviceInfoModel.province;
    _areaModel.city = deviceInfoModel.city;
    _areaModel.distr = deviceInfoModel.district;
    _deviceTypeModel.id = deviceInfoModel.device_type;
    _dno = deviceInfoModel.dno;
//    _deviceTypeModel.name = deviceInfoModel.device_type;
    _companyModel.company_name = deviceInfoModel.company_name;
    _companyModel.id = deviceInfoModel.cid;
    _childCompanyModel.id = deviceInfoModel.child_cid;
    _childCompanyModel.company_name = deviceInfoModel.child_cname;
    _dong = deviceInfoModel.dong;
    _ceng = deviceInfoModel.ceng;
    _fang = deviceInfoModel.fang;
    _lostTime = deviceInfoModel.lose_connection_time;
    if ([deviceInfoModel.is_ignore isEqualToString:@"1"])
    {
        self.switchButton.selected = YES;
    }
    else
    {
        self.switchButton.selected = NO;
    }
    
    
    _isEdit = YES;
    
//    [self.tableView reloadData];
    
}

#pragma mark --- 点击事件
- (void)didClickCommitButton
{
//    if ([_dno isEqualToString:@""])
//    {
//        [SVProgressHUD showErrorWithStatus:@"请扫描设备"];
//        [self.navigationController popViewControllerAnimated:YES];
//        return;
//    }
    
//    if ([_deviceTypeModel.id isEqualToString:@""] || _deviceTypeModel.id == nil)
//    {
//        [SVProgressHUD showErrorWithStatus:@"请选择设备类型"];
//        return;
//    }
    
//    if ([[_areaModel getArea] isEqualToString:@""])
//    {
//        [SVProgressHUD showErrorWithStatus:@"请选择地区"];
//        return;
//    }
    
    if ([_companyModel.id isEqualToString:@""] || _companyModel.id == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择公司"];
        return;
    }
    
    if ([_dong isEqualToString:@""] || _dong == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入栋"];
        return;
    }
    
    if ([_ceng isEqualToString:@""] || _ceng == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入层"];
        return;
    }
    
    if ([_fang isEqualToString:@""] || _fang == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入房"];
        return;
    }
    
//    if ([_lostTime isEqualToString:@""] || _lostTime == nil)
//    {
//        [SVProgressHUD showErrorWithStatus:@"请输入失联时间"];
//        return;
//    }
    
    NSString *is_ignore = @"";
    if (self.switchButton.selected)
    {
        is_ignore = @"1";
    }
    else
    {
        is_ignore = @"0";
    }
    
    if (_isEdit)
    {
        [HYAddOrSaveDeviceApi saveDevice:[NSString stringWithFormat:@"%@",_deviceInfoModel.id]  device_type:_deviceTypeModel.id dno:_dno cid:_companyModel.id child_cid:_childCompanyModel.id dong:_dong ceng:_ceng fang:_fang lose_connection_time:_lostTime is_ignore:is_ignore success:^(NSDictionary *dic) {
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"EditDevice" object:nil userInfo:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        } fail:^(NSDictionary *dic) {
            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        }];
    }
//    else
//    {
//        [HYAddOrSaveDeviceApi addDevice:_deviceTypeModel.id dno:_dno province:_areaModel.province city:_areaModel.city district:_areaModel.distr cid:_companyModel.id child_cid:_childCompanyModel.id dong:_dong ceng:_ceng fang:_fang lose_connection_time:_lostTime is_ignore:is_ignore success:^(NSDictionary *dic) {
//            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self.navigationController popToRootViewControllerAnimated:YES];
//            });
//        } fail:^(NSDictionary *dic) {
//            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
//        }];
//    }
    

    
//    [HYAddOrSaveDeviceApi saveDevice:nil device_type:_deviceTypeModel.id dno:_dno province:_areaModel.province city:_areaModel.city district:_areaModel.distr cid:_companyModel.id child_cid:_childCompanyModel.id dong:_dong ceng:_ceng fang:_fang lose_connection_time:nil is_ignore:nil success:^(NSDictionary *) {
//
//    } fail:^(NSDictionary *dic) {
//
//    }];

}

- (void)didClickSwitchButton
{
    self.switchButton.selected = !self.switchButton.selected;
}

#pragma mark --- 事件处理
- (void)showDevieTypeChoose
{
    [HYDeviceTypeListApi getDeviceType:^(NSArray<HYDeviceTypeModel *> *list) {
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:4];
        for (HYDeviceTypeModel *model in list) {
            [array addObject:model.name];
        }
        __weak typeof(self) weakSelf = self;
        [DTPickerManager shareManager].isFullScreen = 1;
        [DTPickerManager shareManager].dataArray = @[array];
        [[DTPickerManager shareManager] showPickerAndCancel:^(NSArray *arr) {
            
        } andConfirm:^(NSArray *arr) {
            NSInteger index = [arr.firstObject intValue];
            if (list.count == 0) return;
            weakSelf.deviceTypeModel = list[index];
            NSLog(@"%@",weakSelf.deviceTypeModel.name);
            [weakSelf.tableView reloadData];
        }];
    } fail:^(NSDictionary *dic) {
        
    }];

}

- (void)showAreaChoose
{
//    [self hideKeyBoard];
    __weak typeof(self) weakSelf = self;
    TWSelectCityView *city = [[TWSelectCityView alloc] initWithTWFrame:[AppDelegate defaultService].window.bounds TWselectCityTitle:@"选择地区"];
    [city showCityView:^(NSString *proviceStr, NSString *cityStr, NSString *distr) {
        weakSelf.areaModel.province = proviceStr;
        weakSelf.areaModel.city = cityStr;
        weakSelf.areaModel.distr = distr;
        weakSelf.companyModel = nil;
        weakSelf.childCompanyModel = nil;
        [weakSelf.tableView reloadData];
    }];

}

- (void)showCompanyChoose
{
    [HYGetMainCompanyListApi getCompanyMainList:^(NSArray<HYMainCompanyModel *> *list)  {
        __weak typeof(self) weakSelf = self;
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:4];
        for (HYMainCompanyModel *model in list) {
            [array addObject:model.company_name];
        }
        if (array.count == 0)
        {
            [SVProgressHUD showInfoWithStatus:@"无相关公司"];
            return;
        }
        else
        {
            [DTPickerManager shareManager].isFullScreen = 1;
            [DTPickerManager shareManager].dataArray = @[array];
            [[DTPickerManager shareManager] showPickerAndCancel:^(NSArray *arr) {
                
            } andConfirm:^(NSArray *arr) {
                NSInteger index = [arr.firstObject intValue];
                if (list.count == 0) return;
                weakSelf.companyModel = list[index];
                weakSelf.childCompanyModel = nil;
                [weakSelf.tableView reloadData];
                
                [HYGetDeviceAreaApi getDeviceAreaList:[weakSelf.companyModel.id intValue] success:^(NSArray<HYDeviceAreaModel *> *list) {
                    weakSelf.deviceAreaModel = list.firstObject;
                    
                } fail:^(NSDictionary *dic) {
                    
                }];
            }];
        }
       
    } fail:^(NSDictionary *dic) {
        
    }];
}

- (void)showChildCompanyChoose
{
    if (!self.companyModel.id)
    {
        [SVProgressHUD showErrorWithStatus:@"请先选择公司"];
    }
    [HYGetChildCompanyListApi getCompanyChildList:[self.companyModel.id intValue] success:^(NSArray<HYChildCompanyModel *> *list) {
        __weak typeof(self) weakSelf = self;
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:4];
        for (HYChildCompanyModel *model in list) {
            [array addObject:model.company_name];
        }
        if (array.count == 0)
        {
            [SVProgressHUD showInfoWithStatus:@"无分支机构"];
            return;
        }
        else
        {
            [DTPickerManager shareManager].isFullScreen = 1;
            [DTPickerManager shareManager].dataArray = @[array];
            [[DTPickerManager shareManager] showPickerAndCancel:^(NSArray *arr) {
                
            } andConfirm:^(NSArray *arr) {
                NSInteger index = [arr.firstObject intValue];
                if (list.count == 0) return;
                weakSelf.childCompanyModel = list[index];
                [weakSelf.tableView reloadData];
            }];
        }

    } fail:^(NSDictionary *dic) {

    }];
}


- (void)showDongChoose
{
    __weak typeof(self) weakSelf = self;
    if (_deviceAreaModel == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请先选择公司"];
        return;
    }
    NSArray *array = _deviceAreaModel.dong;
    if (array.count == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"没有可选"];
        return;
    }
    [DTPickerManager shareManager].isFullScreen = 1;
    [DTPickerManager shareManager].dataArray = @[array];
    [[DTPickerManager shareManager] showPickerAndCancel:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        
        if (array.count == 0) return;
        weakSelf.dong = array[[arr.firstObject intValue]];
        [weakSelf.tableView reloadData];
    }];
}

- (void)showCengChoose
{
    __weak typeof(self) weakSelf = self;
    if (_deviceAreaModel == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请先选择公司"];
        return;
    }
    NSArray *array = _deviceAreaModel.ceng;
    if (array.count == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"没有可选"];
        return;
    }
    [DTPickerManager shareManager].isFullScreen = 1;
    [DTPickerManager shareManager].dataArray = @[array];
    [[DTPickerManager shareManager] showPickerAndCancel:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        
        if (array.count == 0) return;
        weakSelf.ceng = array[[arr.firstObject intValue]];
        [weakSelf.tableView reloadData];
    }];
}

- (void)showFangChoose
{
    __weak typeof(self) weakSelf = self;
    if (_deviceAreaModel == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请先选择公司"];
        return;
    }
    NSArray *array = _deviceAreaModel.fang;
    if (array.count == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"没有可选"];
        return;
    }
    [DTPickerManager shareManager].isFullScreen = 1;
    [DTPickerManager shareManager].dataArray = @[array];
    [[DTPickerManager shareManager] showPickerAndCancel:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        
        if (array.count == 0) return;
        weakSelf.fang = array[[arr.firstObject intValue]];
        [weakSelf.tableView reloadData];
    }];
}

- (void)showLostTime
{
    __weak typeof(self) weakSelf = self;
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:4];
    for (int i = 1; i <= 100; i ++)
    {
        [array addObject:[NSString stringWithFormat:@"%i",i]];
    }
    [DTPickerManager shareManager].isFullScreen = 1;
    [DTPickerManager shareManager].dataArray = @[array];
    [[DTPickerManager shareManager] showPickerAndCancel:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        weakSelf.lostTime = array[[arr.firstObject intValue]];
        [weakSelf.tableView reloadData];
    }];
}

- (void)showAlertViewWithTitle:(NSString *)title
{
    __weak typeof(self) weakSelf = self;
    [[AlertViewManager shareManager] initWithEditActionTitle:title message:nil cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
        if (buttonIndex == 1) {
            NSString *string = [alertController.textFields.firstObject.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            
            if (string.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@不能为空",title]];
                return;
            }
            if (string.length > 10)
            {
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@不能超过10个字符",title]];
                return;
            }
            
            if ([NSString isContainsEmoji:string])
            {
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@不能使用表情",title]];
                return;
            }
            
            if ([title isEqualToString:@"栋"])
            {
                weakSelf.dong = string;
            }
            else if ([title isEqualToString:@"层"])
            {
                weakSelf.ceng = string;
            }
            else if ([title isEqualToString:@"房"])
            {
                weakSelf.fang = string;
            }
            else if ([title isEqualToString:@"失联时间"])
            {
                NSInteger num = [string intValue];
                if (num <= 0)
                {
                    [SVProgressHUD showErrorWithStatus:@"请输入正确的失联时间"];
                    return;
                }
                weakSelf.lostTime = string;
            }
            [weakSelf.tableView reloadData];
        }
    }];
    
}

#pragma mark - TableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleDataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return px1920Height(150);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditDeviceCell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"EditDeviceCell"];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = fontWithSize(15);
    cell.detailTextLabel.font = fontWithSize(15);

    if (indexPath.row == 5)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        __weak UIView *superView = cell.contentView;
        [superView addSubview:self.switchButton];
        [self.switchButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(superView.mas_centerY);
            make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(40));
        }];
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.textLabel.text = self.titleDataSource[indexPath.row];
//    cell.detailTextLabel.text = self.dataSource[indexPath.row];
    switch (indexPath.row) {
//        case 0:
//            cell.detailTextLabel.text = self.deviceTypeModel.name;
//            break;
//        case 0:
//            cell.detailTextLabel.text = [self.areaModel getArea];
//            break;
        case 0:
            cell.detailTextLabel.text = self.companyModel.company_name;
            break;
        case 1:
            cell.detailTextLabel.text = self.childCompanyModel.company_name;
            break;
        case 2:
            cell.detailTextLabel.text = self.dong;
            break;
        case 3:
            cell.detailTextLabel.text = self.ceng;
            break;
        case 4:
            cell.detailTextLabel.text = self.fang;
            break;
//        case 6:
//            cell.detailTextLabel.text = self.lostTime;
//            break;
        default:
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row)
    {
//        case 0:
//        {
//            [self showDevieTypeChoose];
//        }
//            break;
//        case 0:
//        {
//            [self showAreaChoose];
//        }
//            break;
        case 0:
        {
            [self showCompanyChoose];
        }
            break;
        case 1:
        {
            [self showChildCompanyChoose];
        }
            break;
        case 2:
        {
            [self showAlertViewWithTitle:@"栋"];
//            [self showDongChoose];
        }
            break;
        case 3:
        {
            [self showAlertViewWithTitle:@"层"];
//            [self showCengChoose];
        }
            break;
        case 4:
        {
            [self showAlertViewWithTitle:@"房"];
//            [self showFangChoose];
        }
            break;
//        case 7:
//        {
//            [self showLostTime];
//        }
//            break;
            
        default:
            break;
    }
}

#pragma mark - 懒加载

- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
//        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+px1920Height(30), ZHYScreenWidth, px1920Height(1350)) style:UITableViewStylePlain];
        _tableView = [[UITableView alloc] init];
        [superView addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

//- (NSMutableArray *)dataSource
//{
//    if (!_dataSource)
//    {
//        _dataSource = [NSMutableArray arrayWithArray:@[@"",@"",@"",@"",@"",@"",@"",@"",@""]];
//    }
//    return _dataSource;
//}

- (NSArray *)titleDataSource
{
    if (!_titleDataSource)
    {
        _titleDataSource = @[@"公司",@"分支机构",@"栋",@"层",@"房",@"启用/禁用"];
    }
    return _titleDataSource;
}

- (UIButton *)commitButton
{
    if(!_commitButton)
    {
        UIView *superView = self.view;
        _commitButton = [[UIButton alloc]init];
        [superView addSubview:_commitButton];
        [_commitButton setTitle:@"保存" forState:UIControlStateNormal];
        [_commitButton.titleLabel setFont:fontWithSize(15)];
        [_commitButton setBackgroundImage:[UIImage imageNamed:@"button_login_nor"] forState:UIControlStateNormal];
        [_commitButton addTarget:self action:@selector(didClickCommitButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commitButton;
}

- (UIButton *)switchButton
{
    if(!_switchButton)
    {
        _switchButton = [[UIButton alloc]init];
        [_switchButton setImage:imageWithName(@"but_off") forState:UIControlStateNormal];
        [_switchButton setImage:imageWithName(@"but_on") forState:UIControlStateSelected];
        [_switchButton addTarget:self action:@selector(didClickSwitchButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _switchButton;
}

- (HYDeviceTypeModel *)deviceTypeModel
{
    if(!_deviceTypeModel)
    {
        _deviceTypeModel = [[HYDeviceTypeModel alloc]init];
    }
    return _deviceTypeModel;
}
- (HYAreaModel *)areaModel
{
    if(!_areaModel)
    {
        _areaModel = [[HYAreaModel alloc]init];
        _areaModel.province = @"";
        _areaModel.city = @"";
        _areaModel.distr = @"";
    }
    return _areaModel;
}


#pragma mark - 初始化视图
- (void)base_masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64+px1920Height(30));
        make.left.right.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(900));
    }];
    
    [self.commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_tableView.mas_bottom).with.offset(px1920Height(147));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(66));
        make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(66));
        make.height.mas_equalTo(px1920Height(136));
    }];
    
    superView.backgroundColor = rgba(245,245,245,1);

}


#pragma mark --- 导航栏
- (void)base_configNavigationBar
{
    [self setNavigationTitle:@"编辑" titleColor:[UIColor blackColor]];
    [self setLeftButtonImage:[UIImage imageNamed:@"left"]];
    self.navigationBar.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
